from __future__ import print_function
import os
import sys
import cv2
import matplotlib
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.widgets import Button
from matplotlib.widgets import RectangleSelector

coords = []

def toggle_selector(event):
    if event.key in ['Q', 'q'] and toggle_selector.RS.active:
        toggle_selector.RS.set_active(False)
    if event.key in ['A', 'a'] and not toggle_selector.RS.active:
        toggle_selector.RS.set_active(True)


def line_select_callback(eclick, erelease):
    #'eclick and erelease are the press and release events'
    y1, x1 = eclick.xdata, eclick.ydata
    y2, x2 = erelease.xdata, erelease.ydata
    #print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))
    #print(" The button you used were: %s %s" % (eclick.button, erelease.button))
    coords.append([x1, y1, x2, y2])



def rev_color(img):
	b, g, r = cv2.split(img)
	imn = cv2.merge([r,g,b])
	return imn
    


def recSelectMain(activeframe):
    rectP = dict(facecolor='blue', edgecolor = 'black',
                 alpha=0.15, fill=True)
    lineP = dict(color='blue', linestyle='-',
                 linewidth = 2.5, alpha=0.9)
    #Toggle Selector
    toggle_selector.RS = RectangleSelector(activeframe, line_select_callback,
                                       drawtype='box', useblit=True,
                                       button=[1, 2, 3],  
                                       minspanx=5, minspany=5,
                                       spancoords='pixels',
                                       rectprops=rectP, lineprops=lineP,
                                       interactive=True)
    #Connect actions.
    plt.connect('key_press_event', toggle_selector)   


def clearAll(event):
    plt.close('all')


def getAllArgs(howOut="return"):
	allArgs = sys.argv
	allArgs = allArgs[1:]


	if howOut == "print": 
		print (len(allArgs))
		for i in allArgs: print (i)
	elif howOut == "return":
		return allArgs





def IAR(fileName, verbal=False): 
    #Load the images
    img = rev_color(cv2.imread(fileName))
    pil_img = Image.open(fileName)

    #Main Matplotlib function
    fig = plt.figure(figsize=(6,6)) 
    current_ax = fig.add_subplot(111)
    current_ax.imshow(img)
    #                horz  vert  W    H               
    bLoc = plt.axes([0.70, 0.01, 0.2, 0.05])
    button = Button(bLoc, 'Select')
    button.on_clicked(clearAll)


    recSelectMain(current_ax)

    plt.show()
    #Extracts the selected image
    x1 = int(coords[-1][0])
    y1 = int(coords[-1][1])
    x2 = int(coords[-1][2])
    y2 = int(coords[-1][3])

    img2 = pil_img.crop((y1, x1, y2, x2))

    return img2



def mainRt():
    imgAR = []
    aa = getAllArgs()
    for r, i in enumerate(aa):
        image = IAR(i)
        imgAR.append( image )

    return imgAR
     
def main():
    ai = mainRt()
    for i in ai:
        plt.imshow(i)
        plt.show()
















